import React, { useEffect, useState } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Input, 
  Select, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Upload, 
  Switch,
  Popconfirm,
  Image,
  Row,
  Col,
  Divider,
  DatePicker
} from 'antd';
import { useError } from '../../components/ui/ErrorHandler';
import { useLoading } from '../../components/ui/LoadingManager';
import { 
  PlusOutlined, 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined,
  ExportOutlined,
  ImportOutlined,
  CalendarOutlined,
  EnvironmentOutlined,
  ReloadOutlined,
  TagsOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useCaseStore } from '../../services/store';
import { message } from 'antd';
import { Loading } from '../../components/ui';
import { settingsApi } from '../../services/api';
import { useLocation } from 'react-router-dom';
import type { Case } from '../../types';
import dayjs from 'dayjs';


const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;

interface CaseFormData {
  title: string;
  description: string;
  client: string;
  category: string;
  industry: string;
  location: string;
  duration?: string;
  services: string[];
  highlights: string[];
  images: string[];
  status: 'active' | 'inactive' | 'draft';
  sortOrder: number;
}

const CaseManagePage: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation();
  const { showError } = useError();
  const { withLoading } = useLoading();
  
  const { 
    cases, 
    loading, 
    total, 
    fetchCases, 
    createCase, 
    updateCase, 
    deleteCase 
  } = useCaseStore();
  
  const [modalOpen, setModalOpen] = useState(false);
  const [editingCase, setEditingCase] = useState<Case | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedIndustry, setSelectedIndustry] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [caseCategories, setCaseCategories] = useState<string[]>([]);
  const [categoryManageModalVisible, setCategoryManageModalVisible] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [categoryLoading, setCategoryLoading] = useState(false);
  const [statusOptions] = useState<Array<{value: string, label: string}>>([  
    { value: 'active', label: '启用' },
    { value: 'inactive', label: '停用' }
  ]);

  // 获取案例分类
  const fetchCaseCategories = async () => {
    try {
      const categories = await withLoading(
        settingsApi.getCaseCategories(),
        '正在加载案例分类...'
      );
      // 直接使用返回的字符串数组
      setCaseCategories(Array.isArray(categories) ? categories : ['教育培训', '医疗健康', '商业零售', '政府机关', '工业制造']);
    } catch (error) {
      console.error('获取案例分类失败:', error);
      showError(error instanceof Error ? error : '获取案例分类失败', {
        modal: false,
        details: '将使用默认分类'
      });
      // 使用默认分类
      setCaseCategories(['教育培训', '医疗健康', '商业零售', '政府机关', '工业制造']);
    }
  };

  // 添加分类
  const handleAddCategory = () => {
    if (!newCategoryName.trim()) {
      message.warning('请输入分类名称');
      return;
    }
    setCaseCategories([...caseCategories, newCategoryName.trim()]);
    setNewCategoryName('');
  };

  // 删除分类
  const handleDeleteCategory = (index: number) => {
    const updatedCategories = caseCategories.filter((_, i) => i !== index);
    setCaseCategories(updatedCategories);
  };

  // 保存分类
  const handleSaveCategories = async () => {
    try {
      setCategoryLoading(true);
      await withLoading(
        settingsApi.updateCaseCategories(caseCategories),
        '正在保存案例分类...'
      );
      message.success('案例分类保存成功');
      setCategoryManageModalVisible(false);
    } catch (error) {
      console.error('保存案例分类失败:', error);
      showError(error instanceof Error ? error : '保存案例分类失败', {
        modal: true,
        details: '请检查网络连接或稍后重试'
      });
    } finally {
      setCategoryLoading(false);
    }
  };

  // 获取案例列表
  useEffect(() => {
    fetchCases({
      page: currentPage,
      pageSize,
      keyword: searchKeyword,
      industryId: selectedIndustry === 'all' ? undefined : selectedIndustry,
      status: selectedStatus === 'all' ? undefined : selectedStatus as 'active' | 'inactive'
    });
  }, [currentPage, pageSize, searchKeyword, selectedIndustry, selectedStatus, fetchCases]);

  // 初始化数据
  useEffect(() => {
    fetchCaseCategories();
  }, []);

  // 检查从Dashboard传递的action参数
  useEffect(() => {
    if (location.state?.action === 'create') {
      handleAdd();
      // 清除state以避免重复触发
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  // 筛选处理
  const handleIndustryChange = (value: string) => {
    setSelectedIndustry(value);
    setCurrentPage(1);
  };

  const handleStatusChange = (value: string) => {
    setSelectedStatus(value);
    setCurrentPage(1);
  };

  // 新增案例
  const handleAdd = () => {
    setEditingCase(null);
    form.resetFields();
    form.setFieldsValue({
      status: 'active',
      sortOrder: 0,
      services: [],
      highlights: [],
      images: [],
      industry: '',
      duration: ''
    });
    setModalOpen(true);
  };

  // 编辑案例
  const handleEdit = (caseItem: Case) => {
    setEditingCase(caseItem);
    form.setFieldsValue({
      ...caseItem,
      duration: caseItem.duration || '',
      services: caseItem.services || [],
      highlights: caseItem.highlights || []
    });
    setModalOpen(true);
  };

  // 删除案例
  const handleDelete = async (caseItem: Case) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除案例"${caseItem.title}"吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteCase(caseItem.id);
          message.success('案例已成功删除');
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : '删除案例时发生错误';
          message.error(errorMessage);
        }
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的案例');
      return;
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个案例吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id => deleteCase(id as string))
          );
          setSelectedRowKeys([]);
          message.success(`已成功删除 ${selectedRowKeys.length} 个案例`);
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : '批量删除时发生错误';
          message.error(errorMessage);
        }
      }
    });
  };

  // 刷新页面数据
  const handleRefresh = () => {
    fetchCases({
      page: currentPage,
      pageSize,
      keyword: searchKeyword,
      industryId: selectedIndustry === 'all' ? undefined : selectedIndustry,
      status: selectedStatus === 'all' ? undefined : selectedStatus as 'active' | 'inactive'
    });
    message.success('数据已刷新');
  };

  // 保存案例
  const handleSave = async (values: CaseFormData) => {
    try {
      const formData: CaseFormData = {
        ...values
      };
      
      if (editingCase) {
        await updateCase(editingCase.id, formData);
        message.success('案例信息已成功更新');
      } else {
        await createCase(formData);
        message.success('新案例已成功创建');
      }
      setModalOpen(false);
      form.resetFields();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '操作失败，请重试';
      message.error(errorMessage);
    }
  };

  // 快速切换状态
  const handleStatusToggle = async (caseItem: Case) => {
    try {
      const newStatus = caseItem.status === 'active' ? 'inactive' : 'active';
      await updateCase(caseItem.id, { ...caseItem, status: newStatus });
      message.success(`案例已${newStatus === 'active' ? '启用' : '停用'}`);
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '更新状态时发生错误';
      message.error(errorMessage);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Case> = [
    {
      title: '案例图片',
      dataIndex: 'images',
      key: 'images',
      width: 120,
      render: (images: string[]) => {
        const imageUrl = images?.[0] || 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=case%20study%20placeholder&image_size=square';
        return (
          <Image.PreviewGroup>
            <Image
              width={80}
              height={60}
              src={imageUrl}
              alt="案例图片"
              className="rounded object-cover cursor-pointer"
              preview={{
                src: imageUrl,
                mask: <div className="text-white text-xs">预览</div>
              }}
              fallback=""
            />
            {images && images.length > 1 && (
              <div className="text-xs text-gray-500 mt-1">
                +{images.length - 1} 张图片
              </div>
            )}
          </Image.PreviewGroup>
        );
      }
    },
    {
      title: '案例标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
      sorter: true
    },
    {
      title: '客户名称',
      dataIndex: 'client',
      key: 'client',
      width: 120,
      ellipsis: true
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category: string) => {
        // 获取中文分类名称
        const getCategoryLabel = (cat: string) => {
          // 如果分类本身就是中文名称，直接返回
          if (cat && /[\u4e00-\u9fa5]/.test(cat)) {
            return cat;
          }
          // 兼容旧的英文分类映射
          const categoryMap: { [key: string]: string } = {
            'signage': '标识标牌',
            'led_display': 'LED显示屏',
            'neon_sign': '霓虹灯',
            'acrylic_sign': '亚克力制品',
            'metal_sign': '金属标识',
            'outdoor_ad': '户外广告',
            'indoor_decoration': '室内装饰',
            'exhibition': '展览展示'
          };
          return categoryMap[cat] || cat;
        };
        
        return (
          <Tag color="purple">
            {getCategoryLabel(category) || '未分类'}
          </Tag>
        );
      },
      filters: caseCategories.map(cat => ({ text: cat, value: cat })),
      onFilter: (value, record) => record.category === value
    },
    {
      title: '地点',
      dataIndex: 'location',
      key: 'location',
      width: 100,
      ellipsis: true,
      render: (location: string) => (
        <span>
          <EnvironmentOutlined className="mr-1" />
          {location}
        </span>
      )
    },
    {
      title: '服务内容',
      dataIndex: 'services',
      key: 'services',
      width: 150,
      ellipsis: true,
      render: (services: string[]) => {
        if (!services || services.length === 0) return '-';
        return (
          <div>
            {services.slice(0, 2).map((service, index) => (
              <Tag key={index} color="blue" style={{ marginBottom: 2 }}>
                {service}
              </Tag>
            ))}
            {services.length > 2 && (
              <Tag color="default">+{services.length - 2}</Tag>
            )}
          </div>
        );
      }
    },
    {
      title: '项目周期',
      dataIndex: 'duration',
      key: 'duration',
      width: 150,
      render: (_, record: Case) => {
        if (record.duration) {
          return (
            <span>
              <CalendarOutlined className="mr-1" />
              {record.duration}
            </span>
          );
        }
        return '-';
      },
      sorter: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: Case) => (
        <Switch
          checked={status === 'active'}
          onChange={() => handleStatusToggle(record)}
          checkedChildren="启用"
          unCheckedChildren="停用"
        />
      ),
      filters: statusOptions.map(status => ({ text: status.label, value: status.value })),
      onFilter: (value, record) => record.status === value
    },

    {
      title: '排序',
      dataIndex: 'sortOrder',
      key: 'sortOrder',
      width: 80,
      sorter: true
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record: Case) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => {
              // 预览功能
              message.info('预览功能开发中...');
            }}
          />
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          />
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <Card>
        {/* 页面标题和操作 */}
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">案例管理</h1>
            <p className="text-gray-600 mt-1">管理所有成功案例</p>
          </div>
          <Space>
            <Button icon={<TagsOutlined />} onClick={() => setCategoryManageModalVisible(true)}>
              分类管理
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增案例
            </Button>
          </Space>
        </div>

        {/* 搜索和筛选 */}
        <Row gutter={[16, 16]} className="mb-4">
          <Col xs={24} sm={8} md={6}>
            <Search
              placeholder="搜索案例标题或客户..."
              allowClear
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <Select
              value={selectedIndustry}
              onChange={handleIndustryChange}
              className="w-full"
              placeholder="选择分类"
            >
              <Option value="all">全部分类</Option>
              {caseCategories.filter(category => category && category.trim()).map(category => (
                <Option key={category} value={category}>
                  {category}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={12} sm={8} md={4}>
            <Select
              value={selectedStatus}
              onChange={handleStatusChange}
              className="w-full"
              placeholder="选择状态"
            >
              <Option value="all">全部状态</Option>
              {statusOptions.map((status, index) => (
                <Option key={`status-${status.value}-${index}`} value={status.value}>
                  {status.label}
                </Option>
              ))}
            </Select>
          </Col>
        </Row>

        {/* 批量操作 */}
        {selectedRowKeys.length > 0 && (
          <div className="mb-4 p-3 bg-blue-50 rounded">
            <Space>
              <span>已选择 {selectedRowKeys.length} 项</span>
              <Button size="small" onClick={() => setSelectedRowKeys([])}>
                取消选择
              </Button>
              <Button size="small" danger onClick={handleBatchDelete}>
                批量删除
              </Button>
            </Space>
          </div>
        )}

        {/* 案例表格 */}
        <Table
          columns={columns}
          dataSource={cases}
          rowKey="id"
          loading={loading}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            preserveSelectedRowKeys: true
          }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 案例编辑弹窗 */}
      <Modal
        title={editingCase ? '编辑案例' : '新增案例'}
        open={modalOpen}
        onCancel={() => {
          setModalOpen(false);
          form.resetFields();
        }}
        footer={null}
        width={900}
        destroyOnHidden
        styles={{
          body: {
            maxHeight: '80vh',
            overflowY: 'auto',
            padding: '24px'
          }
        }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="案例标题"
                rules={[{ required: true, message: '请输入案例标题' }]}
              >
                <Input placeholder="请输入案例标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="client"
                label="客户名称"
                rules={[{ required: true, message: '请输入客户名称' }]}
              >
                <Input placeholder="请输入客户名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="案例分类"
                rules={[{ required: true, message: '请选择案例分类' }]}
              >
                <Select placeholder="请选择案例分类">
                  {caseCategories.filter(category => category && category.trim()).map(category => (
                    <Option key={category} value={category}>
                      {category}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="industry"
                label="行业分类"
                rules={[{ required: true, message: '请输入行业分类' }]}
              >
                <Input placeholder="请输入行业分类（如：教育培训、医疗健康等）" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="location"
                label="项目地点"
              >
                <Input placeholder="请输入项目地点" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="startDate"
                label="项目开始时间"
                rules={[{ required: true, message: '请选择项目开始时间' }]}
              >
                <DatePicker className="w-full" placeholder="请选择项目开始时间" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="endDate"
                label="项目结束时间"
                rules={[{ required: true, message: '请选择项目结束时间' }]}
              >
                <DatePicker className="w-full" placeholder="请选择项目结束时间" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="项目周期"
              >
                <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => 
                  prevValues.startDate !== currentValues.startDate || 
                  prevValues.endDate !== currentValues.endDate
                }>
                  {({ getFieldValue }) => {
                    const startDate = getFieldValue('startDate');
                    const endDate = getFieldValue('endDate');
                    if (startDate && endDate) {
                      const duration = dayjs(endDate).diff(dayjs(startDate), 'day');
                      return <Input value={`${duration}天`} disabled />;
                    }
                    return <Input placeholder="自动计算" disabled />;
                  }}
                </Form.Item>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="案例描述"
            rules={[{ required: true, message: '请输入案例描述' }]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入案例描述" 
              showCount 
              maxLength={1000}
            />
          </Form.Item>



          <Form.Item
            name="services"
            label="服务内容"
          >
            <Select
              mode="tags"
              placeholder="请输入服务内容，按回车添加"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="highlights"
            label="项目亮点"
          >
            <Select
              mode="tags"
              placeholder="请输入项目亮点，按回车添加（如：创新设计、环保材料等）"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="challenges"
            label="技术挑战"
          >
            <TextArea 
              rows={3} 
              placeholder="请输入项目中遇到的技术挑战" 
              showCount 
              maxLength={500}
            />
          </Form.Item>



          <Form.Item
            name="images"
            label="案例图片"
          >
            <Upload
              listType="picture-card"
              multiple
              beforeUpload={() => false}
              fileList={[]}
              onChange={(info) => {
                // 这里应该处理图片上传
                console.log('图片上传:', info);
              }}
            >
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
              </div>
            </Upload>
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="status"
                label="发布状态"
                rules={[{ required: true, message: '请选择发布状态' }]}
              >
                <Select>
                  {statusOptions.map(status => (
                    <Option key={status.value} value={status.value}>
                      {status.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>

            <Col span={8}>
              <Form.Item
                name="sortOrder"
                label="排序权重"
                help="数字越小越靠前，0表示按发布时间排序"
              >
                <Input type="number" placeholder="0" min={0} />
              </Form.Item>
            </Col>
          </Row>

          <Divider />

          <div className="flex justify-end space-x-2">
            <Button onClick={() => setModalOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {editingCase ? '更新' : '创建'}
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 分类管理模态框 */}
      <Modal
        title="案例分类管理"
        open={categoryManageModalVisible}
        onCancel={() => setCategoryManageModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setCategoryManageModalVisible(false)}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={handleSaveCategories} loading={categoryLoading}>
            保存
          </Button>,
        ]}
        width={600}
      >
        <div className="space-y-4">
          <div className="flex items-center space-x-2">
            <Input
              placeholder="请输入新的分类名称"
              value={newCategoryName}
              onChange={(e) => setNewCategoryName(e.target.value)}
              onPressEnter={handleAddCategory}
            />
            <Button type="primary" onClick={handleAddCategory}>
              添加分类
            </Button>
          </div>
          
          <div className="max-h-96 overflow-y-auto">
            <div className="space-y-2">
              {caseCategories.map((category, index) => (
                <div key={`category-${category}-${index}`} className="flex items-center justify-between p-3 border rounded-lg">
                  <span className="font-medium">{category}</span>
                  <Button 
                    type="text" 
                    danger 
                    size="small"
                    onClick={() => handleDeleteCategory(index)}
                  >
                    删除
                  </Button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default CaseManagePage;